#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名：tcpclient.py
import codecs
import subprocess
import locale
import socket
import time

# 测试数据常量
BIND_WIDTH = 40
PACKAGE_SIZE = 20

def getstdout(p):
    mylist = []
    while True:
        data = p.stdout.readline()
        if data == b'':
            if p.poll() is not None:
                break
        else:
            mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
    return mylist

MaxBytes = 1024 * 1024
host = '10.112.149.27'
port = 2333
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(30)
client.connect((host, port))
while True:
    inputData = input()  # 等待输入数据
    if inputData == "quit":
        print("我要退出了，再见")
        break
    sendBytes = client.send(inputData.encode())
    if sendBytes <= 0:
        break
    recvData = client.recv(MaxBytes)
    print(recvData.decode())
    if recvData.decode() == "Server has received, iperf3 in server has launched":
        print("开始测试，测试带宽为："+str(BIND_WIDTH)+"MB/s，测量数据的大小为"+str(PACKAGE_SIZE)+"MB，（单位均为字节）")
        for i in range(1, 5):
            print("正在执行第" + str(i) + "次测量")
            ps = subprocess.Popen(
                '.\iperf3.exe -c 10.112.149.27 -u -b ' + str(BIND_WIDTH) + 'M -n ' + str(PACKAGE_SIZE) + 'M',
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                shell=True)
            resultlist = getstdout(ps)
            l = len(resultlist)
            print(resultlist[l - 4])
            speed = str(resultlist[l - 4]).split("  ")[2]
            print(speed)
        client.send("send finished".encode())
    if not recvData:
        print('接收数据为空，我要退出了')
        break
    localTime = time.asctime(time.localtime(time.time()))
    print(localTime, ' 接收到数据字节数:', len(recvData))

client.close()
print("我已经退出了，后会无期")

